package com.ck567.netty.chatroom.server.handler

import com.ck567.netty.chatroom.message.GroupJoinRequestMessage
import com.ck567.netty.chatroom.message.GroupJoinResponseMessage
import com.ck567.netty.chatroom.server.session.GroupSessionFactory
import com.ck567.netty.chatroom.util.logger
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

@ChannelHandler.Sharable
class GroupJoinMessageHandler : SimpleChannelInboundHandler<GroupJoinRequestMessage>() {
    override fun channelRead0(ctx: ChannelHandlerContext, msg: GroupJoinRequestMessage) {
        logger.info("================")
        logger.info("加入群组：$msg")
        val group = GroupSessionFactory.getSession().joinMember(msg.groupName, msg.from)
        if (group != null) {
            ctx.writeAndFlush(GroupJoinResponseMessage(true, "加入成功！"))
            logger.info("加入成功！")
        } else {
            ctx.writeAndFlush(GroupJoinResponseMessage(false,"该群组不存在！"))
            logger.info("该群组不存在！")
        }
    }
    companion object {
        private val logger = logger<GroupJoinMessageHandler>()
    }
}